package com.smiletrain.activities;

import com.smiletrain.R;
import com.smiletrain.base.Usuario;
import com.smiletrain.util.AdminUsuarios;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

public class LoginActivity extends Activity {
	/**
	 * @see android.app.Activity#onCreate(Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        if(AdminUsuarios.instance.getUsuario() != null) {
        	Intent intent = new Intent(LoginActivity.this, WellcomeActivity.class);
			startActivity(intent);
			this.finish();
			return;
        }
        
        setContentView(R.layout.login_view);
        
        txtPassword = (EditText) findViewById(R.id.txtPassword);
        
        sSocio = (Spinner) findViewById(R.id.sSocio);
        
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
                R.array.v00_cbSocio, android.R.layout.simple_spinner_item);
        
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        
        sSocio.setAdapter(adapter);
        
        ImageView bEntrar = (ImageView) findViewById(R.id.bEntrar);
        
        bEntrar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				Usuario u = buildNewUsuario();
				
				if(AdminUsuarios.instance.validarUsuario(u, LoginActivity.this)){
					AdminUsuarios.instance.setUsuario(u);
					Intent intent = new Intent(LoginActivity.this, WellcomeActivity.class);
					startActivity(intent);
				}
			}
			
		});

	}
	
	private Usuario buildNewUsuario() {
		Usuario u = new Usuario();
		
		u.setNombre(sSocio.getSelectedItem().toString());
		u.setPassword(txtPassword.getText().toString());
		u.setSocio(AdminUsuarios.instance.getSocio(u.getNombre()));
		
		return u;
	}
	
	private Spinner sSocio;
	private EditText txtPassword;
	
}
